<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>销售统计</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/app/admin/component/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" media="all">
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <div class="layui-form layui-card-header layuiadmin-card-header-auto">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">日期范围</label>
                            <div class="layui-input-inline">
                                <input type="text" name="date_range" id="date_range" placeholder="请选择日期范围" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">门店</label>
                            <div class="layui-input-inline">
                                <select name="store_id" lay-search>
                                    <option value="">全部门店</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn layuiadmin-btn-list" lay-submit lay-filter="LAY-statistics-search">
                                <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">订单统计</div>
                            <div class="layui-card-body">
                                <div id="order-stats" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">销售趋势</div>
                            <div class="layui-card-body">
                                <div id="sales-trend" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-card">
                    <div class="layui-card-header">商品销量排行</div>
                    <div class="layui-card-body">
                        <table id="LAY-goods-ranking" lay-filter="LAY-goods-ranking"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/app/admin/component/layui/layui.js"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script>
    layui.use(['table', 'form', 'laydate'], function(){
        var $ = layui.$
        ,table = layui.table
        ,form = layui.form
        ,laydate = layui.laydate;
        
        // 初始化图表
        var orderStats = echarts.init(document.getElementById('order-stats'));
        var salesTrend = echarts.init(document.getElementById('sales-trend'));
        
        // 日期范围
        laydate.render({
            elem: '#date_range'
            ,range: true
            ,value: getDefaultDateRange()
        });
        
        // 加载门店列表
        $.get('/app/ky_shouyin/store/getStoreList', function(res){
            if(res.code === 0){
                var html = '<option value="">全部门店</option>';
                layui.each(res.data, function(index, item){
                    html += '<option value="'+ item.id +'">'+ item.name +'</option>';
                });
                $('select[name=store_id]').html(html);
                form.render('select');
                
                // 加载统计数据
                loadStatistics();
            }
        });
        
        // 监听搜索
        form.on('submit(LAY-statistics-search)', function(data){
            loadStatistics(data.field);
            return false;
        });
        
        // 加载统计数据
        function loadStatistics(params){
            params = params || {};
            var dateRange = params.date_range || getDefaultDateRange();
            var dates = dateRange.split(' - ');
            
            $.ajax({
                url: '/app/ky_shouyin/statistics/getSalesData'
                ,type: 'GET'
                ,data: {
                    start_date: dates[0],
                    end_date: dates[1],
                    store_id: params.store_id
                }
                ,success: function(res){
                    if(res.code === 0){
                        renderOrderStats(res.data.order_stats);
                        renderSalesTrend(res.data.daily_sales);
                        renderGoodsRanking(res.data.goods_ranking);
                    }
                }
            });
        }
        
        // 渲染订单统计
        function renderOrderStats(data){
            var option = {
                tooltip: {
                    trigger: 'item'
                },
                series: [
                    {
                        name: '订单统计',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '20',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            {value: data.order_count, name: '订单数量'},
                            {value: data.total_amount, name: '订单金额'}
                        ]
                    }
                ]
            };
            orderStats.setOption(option);
        }
        
        // 渲染销售趋势
        function renderSalesTrend(data){
            var dates = [];
            var amounts = [];
            var counts = [];
            
            layui.each(data, function(index, item){
                dates.push(item.date);
                amounts.push(item.total_amount);
                counts.push(item.order_count);
            });
            
            var option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['订单金额', '订单数量']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: dates
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: '金额',
                        axisLabel: {
                            formatter: '{value} 元'
                        }
                    },
                    {
                        type: 'value',
                        name: '数量',
                        axisLabel: {
                            formatter: '{value} 单'
                        }
                    }
                ],
                series: [
                    {
                        name: '订单金额',
                        type: 'line',
                        data: amounts
                    },
                    {
                        name: '订单数量',
                        type: 'bar',
                        yAxisIndex: 1,
                        data: counts
                    }
                ]
            };
            salesTrend.setOption(option);
        }
        
        // 渲染商品销量排行
        function renderGoodsRanking(data){
            table.render({
                elem: '#LAY-goods-ranking'
                ,data: data
                ,cols: [[
                    {type: 'numbers', title: '排名', width: 80}
                    ,{field: 'name', title: '商品名称', width: 200}
                    ,{field: 'total_quantity', title: '销售数量', width: 120, sort: true}
                    ,{field: 'total_amount', title: '销售金额', width: 120, sort: true}
                ]]
                ,limit: 10
                ,page: false
            });
        }
        
        // 获取默认日期范围（最近7天）
        function getDefaultDateRange(){
            var end = new Date();
            var start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
            return formatDate(start) + ' - ' + formatDate(end);
        }
        
        // 格式化日期
        function formatDate(date){
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            month = month < 10 ? '0' + month : month;
            day = day < 10 ? '0' + day : day;
            return year + '-' + month + '-' + day;
        }
        
        // 窗口大小改变时重绘图表
        window.onresize = function(){
            orderStats.resize();
            salesTrend.resize();
        };
    });
    </script>
</body>
</html> 